<template>
  <div class="form-wrapper">
    <div class="content">
      <div class="content-box">
        <img v-if="showPen" src="@/assets/images/pen.png" class="pen" alt="" />
        <div class="title-box">
          <div class="title">模拟志愿填报</div>
          <div class="desc">输入高考成绩信息，获得精准志愿填报</div>
        </div>
        <div class="form-box">
          <div class="form-item" @click="clickSelectProvince">
            <div class="form-item-title">高考省份</div>
            <div class="form-item-content">
              <div
                :class="[
                  'form-item-content-item',
                  province == '选择省份' ? 'disabled' : '',
                ]"
              >
                {{ province }}
              </div>
              <img
                src="@/assets/images/icon_arrow_next.png"
                class="arrow"
                alt=""
              />
            </div>
          </div>
          <div class="form-item" @click="clickSelectSubject">
            <div class="form-item-title">高考科目</div>
            <div class="form-item-content">
              <div
                :class="[
                  'form-item-content-item',
                  subject == '请选择' ? 'disabled' : '',
                ]"
              >
                {{ subject }}
              </div>
              <img
                src="@/assets/images/icon_arrow_next.png"
                class="arrow"
                alt=""
              />
            </div>
          </div>
          <div class="form-item">
            <div class="form-item-title">高考成绩</div>
            <div class="form-item-content">
              <van-field
                v-show="showInput"
                ref="scoreInputRef"
                class="form-item-content-item"
                type="number"
                label-align="right"
                v-model="score"
                :required="true"
                :border="false"
                :clearable="true"
                :autofocus="true"
                input-align="right"
                placeholder="请输入高考分数"
                @blur="handleScoreInput(false)"
              />
              <div
                v-show="!showInput"
                :class="['form-item-content-item', score ? '' : 'disabled']"
                @click="handleScoreInput(true)"
              >
                {{ score ? score + ' 分' : '请输入分数' }}
              </div>
            </div>
          </div>
          <div class="form-item">
            <div class="form-item-title">高考排名</div>
            <div class="form-item-content">
              <div
                :class="[
                  'form-item-content-item',
                  rank == '请填写' ? 'disabled' : '',
                ]"
              >
                {{ rank }} 位
              </div>
            </div>
          </div>
          <div class="form-item" @click="clickSelectBatchType">
            <div class="form-item-title">院校批次</div>
            <div class="form-item-content">
              <div
                :class="[
                  'form-item-content-item',
                  batchTypeName == '选择批次' ? 'disabled' : '',
                ]"
              >
                {{ batchTypeName }}
              </div>
              <img
                src="@/assets/images/icon_arrow_next.png"
                class="arrow"
                alt=""
              />
            </div>
          </div>
          <div class="tips">
            <div class="tips-item">
              <span class="dot">·</span>
              <span
                >以上数据仅用于模拟志愿功能相关的服务，不会用作其他用途</span
              >
            </div>
            <div class="tips-item">
              <span class="dot">·</span>
              <span
                >暂不支持艺体生等特殊批次学生，招考数据仅供参考，请以当地考试院实际公布为准</span
              >
            </div>
          </div>
          <div class="btn-box">
            <div class="btn" @click="handleStart">开始填报</div>
            <div
              :class="['btn', disabledAI ? 'grey' : 'spe']"
              @click="handleStartAI"
            >
              智能填报
              <!-- <img src="@/assets/images/newIcon.png" class="new-icon" alt="" /> -->
            </div>
          </div>
          <div class="spe-tips">*智能推荐仅供参考，请以实际情况为准</div>
        </div>
      </div>
    </div>
  </div>
  <ProvincePopup
    v-if="isShowProvincePopup"
    :provinces="provinces"
    :selectProvinceObj="selectProvinceObj"
    @onProvinceSelect="onProvinceSelect"
    @onCloseProvince="onCloseProvince"
  >
  </ProvincePopup>

  <SubjectPopup
    v-if="isShowSubjectPopup"
    :propMainSubject="mainMajor"
    :propMinorSubjects="mySelectMinorSubject"
    @onConfirmSubject="onConfirmSubject"
    @onCloseSubject="onCloseSubject(1)"
  >
  </SubjectPopup>

  <TypeTwoSubjectPopup
    v-if="isShowTypeTwoSubjectPopup"
    :subject="subject"
    @onConfirmSubject="onConfirmSubject"
    @onCloseSubject="onCloseSubject(2)"
  >
  </TypeTwoSubjectPopup>

  <TypeThreeSubjectPopup
    v-if="isShowTypeThreeSubjectPopup"
    :subject="subject"
    @onConfirmSubject="onConfirmSubject"
    @onCloseSubject="onCloseSubject(3)"
  >
  </TypeThreeSubjectPopup>

  <BatchTypePopup
    v-if="isShowBatchTypePopup"
    @onConfirmBatchType="onConfirmBatchType"
    @onCloseBatchType="onCloseBatchType"
  >
  </BatchTypePopup>
</template>

<script setup>
import { ref, reactive, nextTick, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { useVolunteerStore } from '@/store/volunteer';
import ProvincePopup from '@/components/ProvincePopup.vue';
import SubjectPopup from './SubjectPopup.vue';
import TypeTwoSubjectPopup from './TypeTwoSubjectPopup.vue';
import TypeThreeSubjectPopup from './TypeThreeSubjectPopup.vue';
import BatchTypePopup from './BatchTypePopup.vue';
import {
  getScoreRank,
  getVolunteerRegion,
  getScoreLine,
  getRegionSearchYear,
  recodeAddOne,
} from '@/api/volunteer';
import { getSubjectIdByName } from '@/utils/subjectData';

const props = defineProps({
  showPen: {
    type: Boolean,
    default: false,
  },
});

const store = useVolunteerStore();
const batchTypeList = computed(() => store.batchTypeList);
const volunteerInfo = computed(() => store.volunteerInfo);

const province = ref('选择省份');
const provinceType = ref(1);
const subject = ref('请选择');
const score = ref('');
const rank = ref('请填写');
const batchType = ref('');
const batchTypeName = ref('选择批次');
const isShowProvincePopup = ref(false);
const isShowSubjectPopup = ref(false);
const isShowBatchTypePopup = ref(false);
const isShowTypeTwoSubjectPopup = ref(false); // 对应返回省份的type是 2
const isShowTypeThreeSubjectPopup = ref(false); // 对应返回省份的type是 3
const router = useRouter();
const selectProvinceObj = reactive({});
const mainMajor = ref('');
const subjectType = ref('');
const provinceId = ref('');
const planYear = ref('2024');
const defaultYear = ref('2024');
const searchRankYear = ref('');
const selectSubjectIds = ref('');
const mySelectMinorSubject = ref([]);

const disabledAI = computed(() => batchTypeName.value.indexOf('提前') > -1);

const showInput = ref(false);

const provinces = ref([]);
const getVolunteerRegionFn = async () => {
  const params = {
    platform: 4,
  };
  const res = await getVolunteerRegion(params);
  if (res.code == 200) {
    provinces.value = [];
    res.data.forEach((item) => {
      provinces.value.push({
        ...item,
        name: item.regionName,
        value: item.regionId,
        select: false,
      });
    });
    store.setProvinces(provinces.value);
  }
};
getVolunteerRegionFn();

const scoreInputRef = ref(null);
const handleScoreInput = (show) => {
  showInput.value = show;
  if (score.value < 100 || score.value > 750) {
    showToast('请输入正确的分数');
    return;
  }
  if (!score.value) return;
  store.setVolunteerInfo(
    Object.assign({}, volunteerInfo.value, {
      score: score.value,
    })
  );
  if (!show) {
    asyncVolunteerInfoFn();
  }
  nextTick(() => {
    if (show) {
      scoreInputRef.value.focus();
    }
  });
};

const clickSelectProvince = () => {
  isShowProvincePopup.value = true;
};

const clickSelectBatchType = () => {
  isShowBatchTypePopup.value = true;
};

const clickSelectSubject = () => {
  switch (provinceType.value) {
    case 1:
      isShowSubjectPopup.value = true;
      break;
    case 2:
      isShowTypeTwoSubjectPopup.value = true;
      break;
    case 3:
      isShowTypeThreeSubjectPopup.value = true;
      break;
    default:
      break;
  }
};

const onProvinceSelect = (item) => {
  if (item.type != provinceType.value) {
    subject.value = '请选择';
    mainMajor.value = '';
    mySelectMinorSubject.value = [];
    selectSubjectIds.value = '';
  }

  isShowProvincePopup.value = false;
  Object.assign(selectProvinceObj, item);
  province.value = item.name;
  provinceType.value = item.type;
  provinceId.value = item.value;
  planYear.value = item.planYear;
  defaultYear.value = item.defaultYear;
  asyncVolunteerInfoFn();
};

const onCloseProvince = () => {
  isShowProvincePopup.value = false;
};

const onConfirmSubject = (type, selectMainSubject, selectMinorSubject) => {
  switch (type) {
    case 1:
      isShowSubjectPopup.value = false;
      mySelectMinorSubject.value = selectMinorSubject;
      mainMajor.value = selectMainSubject;
      subject.value = `${selectMainSubject}、${selectMinorSubject[0]}、${selectMinorSubject[1]}`;
      selectSubjectIds.value = `${getSubjectIdByName(
        selectMainSubject
      )},${getSubjectIdByName(selectMinorSubject[0])},${getSubjectIdByName(
        selectMinorSubject[1]
      )}`;
      subjectType.value = mainMajor.value == '物理' ? '11' : '12';
      asyncVolunteerInfoFn();

      break;
    case 2:
      subjectType.value = '10';
      isShowTypeTwoSubjectPopup.value = false;
      subject.value = selectMainSubject.map((item) => item.name).join('、');
      selectSubjectIds.value = selectMainSubject
        .map((item) => item.id)
        .join(',');
      asyncVolunteerInfoFn();

      break;
    case 3:
      console.log('进入到哦啊啊哈泽丽')
      subjectType.value = '10';
      isShowTypeThreeSubjectPopup.value = false;
      subject.value = selectMainSubject.map((item) => item.name).join('、');
      selectSubjectIds.value = selectMainSubject
        .map((item) => item.id)
        .join(',');
      asyncVolunteerInfoFn();
    default:
      break;
  }
};

const onConfirmBatchType = (item) => {
  batchType.value = item.batchType;
  batchTypeName.value = item.batchTypeName;
  isShowBatchTypePopup.value = false;
};

const onCloseBatchType = () => {
  isShowBatchTypePopup.value = false;
};

const recodeAddOneFn = async (content) => {
  const params = {
    recordType: 10,
    searchContent: JSON.stringify(content),
  };
  const res = await recodeAddOne(params);
};

const handleStartAI = () => {
  if (batchTypeName.value.indexOf('提前') > -1) {
    showToast('智能填报不支持提前批');
    return;
  }

  if (province.value == '选择省份') {
    showToast('请选择省份');
  } else if (subject.value == '请选择') {
    showToast('请选择科目');
  } else if (!score.value) {
    showToast('请输入高考成绩');
  } else if (!rank.value && rank.value != '-') {
    showToast('请获取高考排名');
  } else if (!batchType.value) {
    showToast('请选择院校批次');
  } else {
    if (score.value >= 100 && score.value <= 750) {
      const volunteerInfo = {
        relSubject: selectSubjectIds.value,
        subjectTypeDesc: subject.value,
        subjectType: subjectType.value,
        score: score.value,
        position: rank.value == '-' ? '' : rank.value,
        regionId: provinceId.value,
        regionName: province.value,
        provinceType: provinceType.value,
        planYear: planYear.value,
        defaultYear: defaultYear.value,
        searchRankYear: searchRankYear.value,
        batchType: batchType.value,
        batchTypeName: batchTypeName.value,
      };
      store.setVolunteerInfo(volunteerInfo);
      recodeAddOneFn(volunteerInfo);
      router.push({
        path: '/intelligenceVolunteer',
      });
    } else {
      showToast('请输入正确的分数');
    }
  }
};

const handleStart = () => {
  if (province.value == '选择省份') {
    showToast('请选择省份');
  } else if (subject.value == '请选择') {
    showToast('请选择科目');
  } else if (!score.value) {
    showToast('请输入高考成绩');
  } else if (!rank.value) {
    showToast('请获取高考排名');
  } else {
    if (score.value >= 100 && score.value <= 750) {
      const volunteerInfo = {
        relSubject: selectSubjectIds.value,
        subjectTypeDesc: subject.value,
        subjectType: subjectType.value,
        score: score.value,
        position: rank.value == '-' ? '' : rank.value,
        regionId: provinceId.value,
        regionName: province.value,
        provinceType: provinceType.value,
        planYear: planYear.value,
        defaultYear: defaultYear.value,
        searchRankYear: searchRankYear.value,
        batchType: batchType.value,
        batchTypeName: batchTypeName.value,
      };
      store.setVolunteerInfo(volunteerInfo);
      recodeAddOneFn(volunteerInfo);
      router.push({
        path: '/collegeVolunteer',
      });
    } else {
      showToast('请输入正确的分数');
    }
  }
};
const emit = defineEmits(['changeShowPen']);
// 监听省份，科目，分数的变化
watch(
  [
    provinceId,
    selectSubjectIds,
    subjectType,
    score,
    rank,
    batchType,
    searchRankYear,
  ],
  () => {
    store.setVolunteerInfo(
      Object.assign({}, volunteerInfo.value, {
        relSubject: selectSubjectIds.value,
        subjectType: subjectType.value,
        regionId: provinceId.value,
        regionName: province.value,
        provinceType: provinceType.value,
        planYear: planYear.value,
        defaultYear: defaultYear.value,
        searchRankYear: searchRankYear.value,
        subjectTypeDesc: subject.value,
        score: score.value,
        position: rank.value == '-' ? '' : rank.value,
        batchType: batchType.value,
        batchTypeName: batchTypeName.value,
        searchRankYear: searchRankYear.value,
      })
    );
    if (
      provinceId.value &&
      selectSubjectIds.value &&
      subjectType.value &&
      score.value &&
      rank.value &&
      batchType.value &&
      searchRankYear.value
    ) {
      emit('changeShowPen', false);
    }
  },
  {
    deep: true,
  }
);

const onCloseSubject = (type) => {
  switch (type) {
    case 1:
      isShowSubjectPopup.value = false;
      break;
    case 2:
      isShowTypeTwoSubjectPopup.value = false;
      break;
    case 3:
      isShowTypeThreeSubjectPopup.value = false;
    default:
      break;
  }
};

const getRank = async () => {
  if (
    !provinceId.value ||
    !subjectType.value ||
    score.value < 100 ||
    score.value > 750
  ) {
    return;
  }

  const params = {
    localRegionId: provinceId.value,
    maxScore: score.value,
    recordYear: searchRankYear.value || defaultYear.value,
    subjectType: subjectType.value,
  };

  const res = await getScoreRank(params);
  if (!res || res.code !== 200 || !res.data) {
    return;
  }

  const { minRank } = res.data;
  if (minRank) {
    rank.value = minRank;
  } else {
    rank.value = '-';
  }
};

const getRegionSearchYearFn = async () => {
  const params = {
    localRegionId: provinceId.value,
  };
  const res = await getRegionSearchYear(params);
  if (res.code == 200) {
    searchRankYear.value = res.data.searchYear;
  }
};

const asyncVolunteerInfoFn = async () => {
  await getRegionSearchYearFn();
  await getScoreLineFn();
  await getRank();
};

// 获取院校批次
const getScoreLineFn = async () => {
  if (!provinceId.value || !searchRankYear.value || !subjectType.value) {
    return;
  }
  try {
    const params = {
      localRegionId: provinceId.value,
      recordYear: searchRankYear.value || defaultYear.value,
      subjectType: subjectType.value,
    };
    const res = await getScoreLine(params);
    if (res.code == 200 && res.data.length > 0) {
      const temp = res.data.map((item) => {
        return {
          ...item,
          cateTypeName: item.cateType == 30 ? '本科批' : '专科批',
        };
      });
      store.setBatchTypeList(temp);
      confirmBatchType(); // 自动匹配批次类型
    }
  } catch (error) {
    console.log(error);
  }
};
const confirmBatchType = () => {
  if (
    province.value == '选择省份' ||
    subject.value == '请选择' ||
    !score.value ||
    !rank.value
  ) {
    return;
  }
  // 判断当前score和batchTypeList数组中的lineScore的大小关系，如果score大于等于lineScore
  const temp = batchTypeList.value.find(
    (item) => score.value >= item.lineScore
  );
  batchTypeName.value = temp ? temp.batchTypeName : '选择批次';
  batchType.value = temp ? temp.batchType : '11';
  store.setVolunteerInfo(
    Object.assign({}, volunteerInfo.value, {
      batchType: temp ? temp.batchType : '11',
      batchTypeName: temp ? temp.batchTypeName : '本科普通批',
    })
  ); //要存，不然点击选择还是以前的
  store.setDefaultBatchType(batchType.value);
  store.setDefaultCateType(temp ? temp.cateType : '30'); //  存一下，后面有用
};

const getCacheData = (info) => {
  if (!info) return;
  const {
    relSubject,
    subjectTypeDesc,
    subjectType: tempSubjectType,
    score: infoScore,
    position,
    regionId,
    planYear: infoPlanYear,
    regionName,
    provinceType: infoProvinceType,
    searchRankYear: infoSearchRankYear,
    batchType: infoBatchType,
    batchTypeName: infoBatchTypeName,
  } = info;
  // 设置科目相关信息
  if (relSubject) {
    selectSubjectIds.value = relSubject;
  }

  if (subjectTypeDesc) {
    subject.value = subjectTypeDesc;
    const names = subjectTypeDesc.split('、');
    mainMajor.value = names[0];
    mySelectMinorSubject.value = names.slice(1);
  }

  if (tempSubjectType) {
    subjectType.value = tempSubjectType;
  }

  // 设置分数和排名
  if (infoScore) {
    score.value = infoScore;
  }

  if (position) {
    rank.value = position;
  }

  // 设置地区相关信息
  if (regionId) {
    provinceId.value = regionId;
  }

  if (infoPlanYear) {
    planYear.value = infoPlanYear;
  }

  if (regionName) {
    province.value = regionName;
    Object.assign(selectProvinceObj, {
      name: regionName,
      value: regionId,
      type: infoProvinceType || 1,
      select: true,
    });
    provinceType.value = infoProvinceType || 1;
  }

  if (infoSearchRankYear) {
    searchRankYear.value = infoSearchRankYear;
  }

  if (infoBatchType) {
    batchType.value = infoBatchType;
  }

  if (infoBatchTypeName) {
    batchTypeName.value = infoBatchTypeName;
  }
};

getCacheData(volunteerInfo.value);

asyncVolunteerInfoFn();

watch(
  volunteerInfo,
  (newVal) => {
    if (newVal.value?.relSubject) {
      getCacheData(newVal);
    }
  },
  {
    deep: true,
  }
);
</script>

<style scoped lang="scss">
.form-wrapper {
  .content {
    .content-box {
      position: relative;
      .pen {
        position: absolute;
        top: -65px;
        right: -90px;
        width: 355px;
        height: 390px;
      }
      .title-box {
        .title {
          font-size: 50px;
          color: #000000;
          font-weight: bold;
          line-height: 60px;
        }
        .desc {
          margin-top: 22px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 26px;
          color: #555555;
          line-height: 33px;
        }
      }
      .form-box {
        margin-top: 52px;
        width: 100%;
        box-sizing: border-box;
        padding: 48px 32px;
        position: relative;
        border-radius: 32px;
        background-color: #f6fbfe;
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          border-radius: 32px;
          padding: 2px;
          background: linear-gradient(
            180deg,
            rgba(255, 255, 255, 1),
            rgba(206, 231, 245, 1)
          );
          -webkit-mask: linear-gradient(#fff 0 0) content-box,
            linear-gradient(#fff 0 0);
          mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
          -webkit-mask-composite: xor;
          mask-composite: exclude;
          pointer-events: none;
        }
        .form-item {
          position: relative;
          z-index: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 24px 0;
          border-bottom: 1px solid $border-color;
          font-weight: bold;
          &:first-child {
            padding-top: 0;
          }
          .form-item-title {
            display: flex;
            align-items: center;
            font-size: 26px;
            color: $title-color;
            font-weight: bold;
            line-height: 33px;
          }
          .form-item-content {
            display: flex;
            align-items: center;
            font-size: 26px;
            color: $title-color;
            .form-item-content-item {
              padding: 0;
              margin-right: 12px;
              &.disabled {
                color: #999;
              }
            }
            .arrow {
              width: 30px;
              height: 30px;
            }
            :deep(.van-field) {
              background-color: #f6fbfe;
              .van-field__control {
                font-size: 26px;
                color: #000000;
              }
            }
          }
        }
        .tips {
          margin-top: 34px;
          font-size: 22px;
          color: $title-color;
          .tips-item {
            font-weight: 400;
            font-size: 20px;
            color: #888888;
            line-height: 26px;
            display: flex;
            .dot {
              margin-right: 6px;
              font-size: 30px;
            }
            &:first-child {
              margin-bottom: 12px;
            }
          }
        }
        .btn-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .btn {
            width: 48%;
            text-align: center;
            background: $primary-color;
            border-radius: 12px;
            font-weight: bold;
            font-size: 26px;
            color: #ffffff;
            margin-top: 40px;
            padding: 16px 0;
          }
          .spe {
            position: relative;
            background: linear-gradient(240deg, #597dff 0%, #9d19ff 100%);
          }
          .new-icon {
            position: absolute;
            top: -18px;
            right: 14px;
            width: 72px;
            height: 40px;
          }
          .grey {
            position: relative;
            background: #b2b4b8;
          }
        }
        .spe-tips {
          margin-left: auto;
          text-align: right;
          font-size: 20px;
          color: #912bff;
          line-height: 25px;
          margin-top: 18px;
        }
      }
    }
  }
}
</style>
